package com.ycfmedical.bed.utils;

import java.util.ArrayList;
import java.util.List;

import com.ycfmedical.bed.bean.EntertainItem;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

/**
 * 音乐工具类 Created by Egoist on 2017/1/19.
 */

public class MusicUtils
{
    /**
     * 扫描系统里面的音频文件，返回一个list集合
     */
    public static List<EntertainItem> getMusicData(Context context)
    {
        List<EntertainItem> list = new ArrayList<EntertainItem>();
        // 媒体库查询语句（写一个工具类MusicUtils）
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            MediaStore.Audio.AudioColumns.IS_MUSIC);
        if (cursor != null)
        {
            while (cursor.moveToNext())
            {
                EntertainItem entertainItem = new EntertainItem();
                entertainItem.name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                entertainItem.artist= cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                entertainItem.id= cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                entertainItem.path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                entertainItem.album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                entertainItem.duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                entertainItem.size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                if (entertainItem.size > 1000 * 800)
                {
                    // 注释部分是切割标题，分离出歌曲名和歌手 （本地媒体库读取的歌曲信息不规范）
                    if (entertainItem.name.contains("-"))
                    {
                        String[] str = entertainItem.name.split("-");
                        entertainItem.artist = str[0];
                        entertainItem.name = str[1];
                    }
                    list.add(entertainItem);
                }
            }
            // 释放资源
            cursor.close();
        }

        return list;
    }

    /**
     * 定义一个方法用来格式化获取到的时间
     */
    public static String formatTime(int time)
    {
        if (time / 1000 % 60 < 10)
        {
            return time / 1000 / 60 + ":0" + time / 1000 % 60;

        }
        else
        {
            return time / 1000 / 60 + ":" + time / 1000 % 60;
        }

    }

    // 通过AlbumId 查询封面
    public static Uri getAlbumArtUri(long albumId) {
        return ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId);
    }
}
